import React, {Component} from 'react'
import {Button, Divider, Row} from 'antd'
import {withRouter} from 'react-router-dom'
import {connect} from 'react-redux'
import SearchBox from '../common/search-box'
import QuizzesTable from './quizzes-table'

import * as actions from '../../actions/logic-quiz'
import {FormattedMessage} from 'react-intl'

class LogicQuizzes extends Component {
  constructor (props) {
    super(props)
    this.state = {
      page: 1,
      pageSize: 10,
      searchConditions: {}
    }
  }

  componentDidMount () {
    this.props.getLogicQuizzes()
  }

  onChange (page) {
    this.setState({page})
    const {pageSize, searchConditions} = this.state
    this.props.getLogicQuizzes(page, pageSize, searchConditions)
  }

  onSearch (searchConditions) {
    const defaultPage = 1
    this.setState({searchConditions})
    const {pageSize} = this.state
    this.props.getLogicQuizzes(defaultPage, pageSize, searchConditions)
  }
  editorQuiz (id) {
    this.props.history.push(`/logicQuizzes/${id}/editor`)
  }

  addQuiz () {
    this.props.history.push(`/logicQuizzes/new`)
  }

  deleteQuiz (quizId) {
    this.props.deleteQuiz(quizId)
  }

  render () {
    const dataSource = this.props.logicQuizzes.content || []
    const pagination = {
      current: this.state.page,
      total: this.props.logicQuizzes.totalElements,
      pageSize: this.state.pageSize,
      onChange: (page) => {
        this.onChange(page, this.state.pageSize)
      }
    }
    return (
      <div>
        <Row>

          <Button type='primary' onClick={this.addQuiz.bind(this)}><FormattedMessage id='新增' /></Button>
        </Row>
        <Row>
          <SearchBox onSearch={this.onSearch.bind(this)} hideTagsInput />
        </Row>
        <Divider type='horizontal' />
        <QuizzesTable
          dataSource={dataSource}
          pagination={pagination}
          onShowEditorPage={this.editorQuiz.bind(this)}
          onDeleteQuiz={this.deleteQuiz.bind(this)}
          type='LOGIC_QUIZ'

        />
      </div>
    )
  }
}
const mapStateToProps = ({logicQuizData}) => ({
  logicQuizzes: logicQuizData.logicQuizzes
})

const mapDispatchToProps = dispatch => ({
  getLogicQuizzes: (page, pageSize, searchConditions) => dispatch(actions.getLogicQuizzes(page, pageSize, searchConditions)),
  deleteQuiz: (quizId) => dispatch(actions.deleteQuiz(quizId))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(LogicQuizzes))
